package base.hash;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;

/**
 * @author G_Y
 * 2018年3月14日
 * 说明:Sha256 散列
 */
public class Sha256Main {

	public static void main(String[] args) {
		//System.out.println(0b110);
		/*String s = "110";
		String type = "SHA-256";
		//利用java自带的实现加密
		String result = sign(s, type);
		System.out.println(result.length());
		System.out.println(result);
		//利用Apache的工具类实现加密
		System.out.println(getSHA256Str(s));*/

		JmhbUtils.getAllJmhb();
		
	}

	public static String sign(String str, String type) {
		String s = Encrypt(str, type);
		return s;
	}

	/**
	 * @param strSrc
	 * @param encName
	 * @return
	 * G_Y
	 * 2018年3月14日
	 * 说明:利用java自带的实现加密
	 */
	public static String Encrypt(String strSrc, String encName) {
		MessageDigest md = null;
		String strDes = null;
		byte[] bt = strSrc.getBytes();
		try {
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			strDes = bytes2Hex(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			System.out.println("签名失败！");
			return null;
		}
		return strDes;
	}

	
	public static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}

	/**
	 * @param str
	 * @return
	 * G_Y
	 * 2018年3月14日
	 * 说明:利用Apache的工具类实现加密
	 */
	public static String getSHA256Str(String str) {
		MessageDigest messageDigest;
		char[] encdeStr = null;
		try {
			messageDigest = MessageDigest.getInstance("SHA-256");
			byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
			encdeStr = Hex.encodeHex(hash);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return String.valueOf(encdeStr);
	}

}
